package util

import (
	"encoding/json"
	"gobase/app/model"
)

//树结构
type TreeNode struct {
	Id       int
	Title    string
	Children []*TreeNode
}

func newTreeNode(id int, title string, c []*TreeNode) *TreeNode {
	return &TreeNode{Id: id, Title: title, Children: c}
}

//构造资源树JSON
func GetResourceTree(list []*model.Resource) string {
	result := make(map[int]*TreeNode)

	for _, v := range list {
		id := v.Id
		title := v.Title

		if v.ParentId == 0 {
			tn := newTreeNode(id, title, []*TreeNode{})
			result[id] = tn
			addResourceChildren(tn, list)
		}
	}

	jsonRes, _ := json.Marshal(result)
	return string(jsonRes)
}

func addResourceChildren(tn *TreeNode, list []*model.Resource) {
	c := tn.Children
	for _, v := range list {
		if v.ParentId == tn.Id {
			c1 := newTreeNode(v.Id, v.Title, []*TreeNode{})
			c = append(c, c1)
			addResourceChildren(c1, list)
		}
	}
	tn.Children = c
}
